"""
    Created By Khun on 2020/4/11
"""

__author__ = 'Khun'

from flask import render_template, request, redirect, url_for, abort, current_app, flash
from flask_login import login_required
from sqlalchemy import desc, or_

from app.forms.wechat import ThrowForm, SearchForm
from app.models import db, Throw
from app.vipadmin import vipadmin


@vipadmin.route('/throw/list/<int:page>', methods=['GET', 'POST'])
@login_required
def throw_list(page):
    """ 投放模板 """
    page_data = Throw.query.order_by(desc(Throw.tid)).paginate(page=page, per_page=current_app.config['PAGE_SIZE'])

    return render_template('throw/throw_list.html', page_data=page_data)


@vipadmin.route('/throw/add', methods=['GET', 'POST'])
@login_required
def throw_add():
    form = ThrowForm()
    if request.method == 'POST' and form.validate_on_submit():
        throw = Throw()
        throw.set_attr(form.data)
        with db.auto_commit():
            db.session.add(throw)
        flash('新增成功', 'success')
        return redirect(url_for('vipadmin.throw_list', page=1))
    elif form.errors:
        flash('检查数据是否有误', 'danger')
    return render_template('throw/throw_add.html', form=form)


@vipadmin.route('/throw/delete/<int:tid>', methods=['GET', 'POST'])
@login_required
def throw_delete(tid):
    throw_obj = Throw.query.filter_by(tid=tid).first()
    if request.method == 'POST' and throw_obj is None:
        abort(404)
    with db.auto_commit():
        db.session.delete(throw_obj)
    flash('删除成功', 'success')
    return redirect(url_for('vipadmin.throw_list', page=1))


@vipadmin.route('/throw/edit/<tid>', methods=['GET', 'POST'])
@login_required
def throw_edit(tid):
    # 获取模板id
    throw_obj = Throw.query.filter_by(tid=tid).first()

    if request.method == 'POST' and throw_obj is None:
        abort(404)
    data = ThrowForm(obj=throw_obj)
    if request.method == 'POST' and data.validate_on_submit():
        throw_obj.set_attr(data.data)

        with db.auto_commit():
            db.session.add(throw_obj)
        flash('修改成功', 'success')
        return redirect(url_for('vipadmin.throw_list', page=1))
    elif data.errors:
        flash('检查数据是否有误', 'danger')
    return render_template('throw/throw_edit.html', data=data, throw_obj=throw_obj)


@vipadmin.route('/throw/search', methods=['GET'])
@login_required
def throw_search():
    """ 域名或者微信号搜索 """
    form = SearchForm(request.args)
    result = []
    q = ''
    if form.validate():
        q = form.q.data.strip()
        page = form.page.data
        result = Throw.query.filter(
            or_(Throw.temp_name.like('%' + q + '%'),
                Throw.temp_path.like('%' + q + '%'))
        ).order_by(desc(Throw.tid)).paginate(page=page, per_page=current_app.config['PAGE_SIZE'])
    try:
        return render_template('throw/search_result.html', page_data=result, q=q)
    except Exception as e:
        return '<h2 style="color:red;text-align:center">搜索内容不能为空,请手动返回，重新搜索！</h2>'
